import type { IUser, IServerInfo, ISwitch } from '@/api/global/interface'
import create from 'zustand'
import { persist, createJSONStorage, subscribeWithSelector } from 'zustand/middleware'

interface GlobalState {
	user: IUser | null
	setUser: (u: IUser) => void
	serverInfo: IServerInfo | null
	setServerInfo: (u: IServerInfo) => void
	//为了区别请求ok还是session缓存
	userLoaded: boolean
	serverLoaded: boolean
	//针对国际化 功能显示权限
	SWITCH: ISwitch
}

//缓存用户的部分信息，尽量保证头部用户名和导航条不跳变
export const useGlobalStore = create<GlobalState>()(
	subscribeWithSelector(
		/*
		zustand提供一个persist的中间件，这个中间件通过localStorage来持久化数据
		*/
		persist(
			(set) => ({
				user: null,
				setUser: (u) => set({ user: u, userLoaded: true }),
				serverInfo: null,
				setServerInfo: (u) => set({ serverInfo: u, serverLoaded: true }),
				userLoaded: false,
				serverLoaded: false,
				SWITCH: window.__SWITCH__,
			}),
			{
				name: 'cfg',
				storage: createJSONStorage(() => sessionStorage),
				partialize: (state) => ({
					user: {
						enable_meeting: state.user?.enable_meeting,
						enable_cms_approval: state.user?.enable_cms_approval,
						is_meeting_admin: state.user?.is_meeting_admin,
						name: state.user?.name,
						moid: state.user?.moid,
					},
				}),
			}
		)
	)
)
